`timescale 1ns/1ns
/*题目描述：
请编写一个信号发生器模块，根据波形选择信号wave_choise发出相应的波形：
wave_choice=0时，发出方波信号；
wave_choice=1时，发出锯齿波信号；
wave_choice=2时，发出三角波信号。
*/
module signal_generator(
	input clk,
	input rst_n,
	input [1:0] wave_choise,
	output reg [4:0]wave
	);

    reg [4:0] cnt;
    reg flag;

    always @(posedge clk or negedge rst_n)
    begin
        if (!rst_n)
            cnt<=0;
        else
        begin
            if (wave_choise==0)
            begin
                if (cnt>=19)
                    cnt<=0;
                else
                    cnt<=cnt+1;
            end
            else
                cnt<=0;
        end
    end

    always @(posedge clk or negedge rst_n)
    begin
        if (!rst_n)
            flag<=1;
        else
        begin
            if (wave_choise==2)
            begin
                if (wave==19)
                    flag<=1;
                else if (wave==1)
                    flag<=0;
                else
                    flag<=flag;
            end
            else
            begin
                if (wave==0)
                    flag<=0;
                else
                    flag<=1;
            end
        end
    end

    always @(posedge clk or negedge rst_n)
    begin
        if (!rst_n)
            wave<=0;
        else
        begin
            if (wave_choise==0)
            begin
                wave <= cnt<9?    0     :
                                cnt<19?20:0;
            end
            else if (wave_choise==1)
            begin
                wave <= wave>=20? 0     : wave+1;
            end
            else if (wave_choise==2)
            begin
                wave <= flag==1 ? wave-1: wave+1;
            end
            else
                wave<=0;
        end
    end



endmodule
